package com.villaday.idf.activity;

import android.Manifest;
import android.content.ContentResolver;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.provider.ContactsContract;
import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import androidx.viewpager.widget.ViewPager;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;
import android.text.Html;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.atuan.datepickerlibrary.CalendarUtil;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.google.gson.Gson;
import com.villaday.idf.R;
import com.villaday.idf.adapter3.OrderDeatailsPopuAdapter;
import com.villaday.idf.adapter3.OrderInputAdapter;
import com.villaday.idf.adapter3.PopularHouseAdapter;
import com.villaday.idf.base.BaseActivity;
import com.villaday.idf.custom.CommonPopupWindow;
import com.villaday.idf.custom.ConfirmReturnDialog;
import com.villaday.idf.custom.LoadDialog;
import com.villaday.idf.custom.bannerUtil.BannerUtils;
import com.villaday.idf.model3.CreatOrdersEntity;
import com.villaday.idf.model3.DataEntity;
import com.villaday.idf.model3.GuestPostEntity;
import com.villaday.idf.model3.HotelDetailsEntity;
import com.villaday.idf.model3.HotelRoomEntity;
import com.villaday.idf.model3.MemberGuestEntity;
import com.villaday.idf.model3.OrderPrepareEntity;
import com.villaday.idf.model3.OrderPreparePostEntity;
import com.villaday.idf.model3.OrdersPostEntity;
import com.villaday.idf.util.Constant;
import com.villaday.idf.util.LogUtil;
import com.villaday.idf.util.OkHttpUtil;
import com.villaday.idf.util.RegexUtil;
import com.villaday.idf.util.ToastUtil;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import butterknife.OnTextChanged;

public class OrderInputActivity extends BaseActivity {


    @BindView(R.id.iv_title)
    ImageView ivTitle;
    @BindView(R.id.iv_title_right)
    ImageView ivTitleRight;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_title_big)
    TextView tvTitleBig;
    @BindView(R.id.tv_title_en)
    TextView tvTitleEn;
    @BindView(R.id.tv_oi_title)
    TextView tvOiTitle;
    @BindView(R.id.tv_oi_details)
    TextView tvOiDetails;
    @BindView(R.id.iv_oi_more)
    ImageView ivOiMore;
    @BindView(R.id.ll_ol_house_details)
    LinearLayout llOlHouseDetails;
    @BindView(R.id.tv_oi_time)
    TextView tvOiTime;
    @BindView(R.id.tv_oi_time_right)
    TextView tvOiTimeRight;
    @BindView(R.id.tv_oi_bottom)
    TextView tvOiBottom;
    @BindView(R.id.tv_oi_max)
    TextView tvOiMax;
    @BindView(R.id.iv_oi_reduce)
    ImageView ivOiReduce;
    @BindView(R.id.tv_home_num)
    TextView tvHomeNum;
    @BindView(R.id.iv_oi_add)
    ImageView ivOiAdd;
    @BindView(R.id.rv_oi_in)
    RecyclerView rvOiIn;
    @BindView(R.id.et_oi_phone)
    EditText etOiPhone;
    @BindView(R.id.iv_oi_phone)
    ImageView ivOiPhone;
    @BindView(R.id.tv_oi_error)
    TextView tvOiError;
    @BindView(R.id.ll_oi_error)
    LinearLayout llOiError;
    @BindView(R.id.et_oi_email)
    EditText etOiEmail;
    @BindView(R.id.ll_oi_email)
    LinearLayout llOiEmail;
    @BindView(R.id.tv_reduce_me)
    TextView tvReduceMe;
    @BindView(R.id.ll_reduce_me)
    LinearLayout llReduceMe;
    @BindView(R.id.tv_reduce_old)
    TextView tvReduceOld;
    @BindView(R.id.ll_reduce_old)
    LinearLayout llReduceOld;
    @BindView(R.id.iv_balance)
    ImageView ivBalance;
    @BindView(R.id.iv_balance_title)
    TextView ivBalanceTitle;
    @BindView(R.id.tv_oi_has)
    TextView tvOiHas;
    @BindView(R.id.iv_balance_check)
    ImageView ivBalanceCheck;
    @BindView(R.id.iv_balance_check_money)
    TextView ivBalanceCheckMoney;
    @BindView(R.id.rl_ol_hava)
    RelativeLayout rlOlHava;
    @BindView(R.id.ll_reduce_reduce)
    LinearLayout llReduceReduce;
    @BindView(R.id.et_oi_num)
    TextView tvOiNum;
    @BindView(R.id.et_oi_feedBack)
    EditText etOiFeedBack;
    @BindView(R.id.tv_oi_left)
    TextView tvOiLeft;
    @BindView(R.id.tv_oi_money)
    TextView tvOiMoney;
    @BindView(R.id.tv_oi_reduce)
    TextView tvOiReduce;
    @BindView(R.id.tv_oi_confirm)
    TextView tvOiConfirm;
    @BindView(R.id.tv_oi_details_more)
    TextView tvOiDetailsMore;
    @BindView(R.id.iv_oi_details)
    ImageView ivOiDetails;
    @BindView(R.id.ll_ol_details)
    LinearLayout llOlDetails;
    @BindView(R.id.vw_email)
    View vwEmail;
    @BindView(R.id.ll_oi_money)
    LinearLayout llOiMoney;
    @BindView(R.id.ll_ol)
    LinearLayout llOl;
    @BindView(R.id.vw_ol_add)
    View vwOlAdd;
    @BindView(R.id.tv_ol_add)
    TextView tvOlAdd;
    @BindView(R.id.tv_reduce_me_left)
    TextView tvReduceMeLeft;
    @BindView(R.id.tv_reduce_old_left)
    TextView tvReduceOldLeft;
    @BindView(R.id.ll_bottom)
    LinearLayout llBottom;


    private int homeDay = 1;//房间天数
    private int homeNum = 1;//房间数量
    private int minNum = 1;//最小数量
    private int maxNum = 0;//最大数量
    private boolean userBalance = false;//是否使用余额

    private HotelRoomEntity.BodyBean mBodyBean;
    private HotelRoomEntity.BodyBean.SalePlansBean mSalePlansBean;
    private HotelDetailsEntity.BodyBean mDetailsBean;

    private int promotionNum = 0;//使用余额数量

    private String mCheckOutDate = "2019-07-26";
    private String mCheckInDate = "2019-07-25";
    private String mAddress = "湖南省";

    private OrderPrepareEntity mOrderPrepareEntity;
    private List<GuestPostEntity> listData = new ArrayList<>();
    private OrderInputAdapter orderInputAdapter;
    private CommonPopupWindow popuDetails;
    private CommonPopupWindow popupMore;

    private TextView tvGuideMore;

    private boolean mIsIdentity;
    private OrderPrepareEntity.BodyBean mPrepareBody;
    private LoadDialog loadDialog;
    private int position;
    private MemberGuestEntity mReturnEntity;


    @Override
    protected int getViewResId() {
        return R.layout.activity_order_input;
    }


    @Override
    protected void init() {
        super.init();

        //初始化数据
        initData();
        //初始化列表
        initRecycle();
        //预订单
        initPrepare();
    }

    private void initData() {
        try {
            String dataDetails = getIntent().getExtras().getString("dataDetails");
            mDetailsBean = new Gson().fromJson(dataDetails, HotelDetailsEntity.BodyBean.class);

            String data = getIntent().getExtras().getString("data");
            mBodyBean = new Gson().fromJson(data, HotelRoomEntity.BodyBean.class);
            position = getIntent().getExtras().getInt("position");
            mSalePlansBean = mBodyBean.getSalePlans().get(position);

            mCheckOutDate = getIntent().getExtras().getString("checkOutDate");
            mCheckInDate = getIntent().getExtras().getString("checkInDate");
            String inDay = getIntent().getExtras().getString("inDay");


            tvOiTime.setText(CalendarUtil.FormatChangeString(mCheckInDate) + " - " + CalendarUtil.FormatChangeString(mCheckOutDate));
            tvOiTimeRight.setText(inDay);
            homeDay = Integer.parseInt(inDay.replace("晚", ""));


            //是否国外酒店
            if (mDetailsBean.getDistrict() == 3) {//国外酒店
                tvTitleBig.setVisibility(View.GONE);

                tvTitle.setVisibility(View.VISIBLE);
                tvTitle.setText(mDetailsBean.getName());

                tvTitleEn.setVisibility(View.VISIBLE);
                tvTitleEn.setText(mDetailsBean.getNameEn());
            } else {
                tvTitleBig.setVisibility(View.VISIBLE);
                tvTitleBig.setText(mDetailsBean.getName());
                tvTitle.setVisibility(View.GONE);
                tvTitleEn.setVisibility(View.GONE);
            }

            tvOiLeft.setText(Html.fromHtml("&yen;"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成预订单
     */
    private void initPrepare() {
        showDialog();
        OrderPreparePostEntity orderPreparePostEntity = new OrderPreparePostEntity();
        orderPreparePostEntity.setType(15);
        OrderPreparePostEntity.ProductBean productBean = new OrderPreparePostEntity.ProductBean();
        productBean.setId(mDetailsBean.getId());
        productBean.setRoomTypeId(mBodyBean.getId());
        productBean.setSalePlanId(mSalePlansBean.getId());
        productBean.setType(99);
        productBean.setQuantity(homeNum);
        orderPreparePostEntity.setProduct(productBean);
        orderPreparePostEntity.setUseWallet(userBalance);
        orderPreparePostEntity.setCheckInDate(mCheckInDate);
        orderPreparePostEntity.setCheckOutDate(mCheckOutDate);

        Map<String, Object> map = new HashMap<>();
        OkHttpUtil.postJson(this, Constant.URL.prepare, orderPreparePostEntity, map, new OkHttpUtil.OnDataListener() {

            @Override
            public void onResponse(String url, String json) {
                try {
                    LogUtil.jLog().e(json);
                    dismissDialog();
                    if (!TextUtils.isEmpty(json)) {
                        mOrderPrepareEntity = new Gson().fromJson(json, OrderPrepareEntity.class);
                        if (mOrderPrepareEntity.getCode().equals(Constant.Strings.SUC)) {
                            mPrepareBody = mOrderPrepareEntity.getBody();

                            minNum = mPrepareBody.getQuantityLower();
                            maxNum = mPrepareBody.getQuantityUpper();
                            if (maxNum != 0) {
                                tvOiMax.setText("限购" + maxNum + "间");
                            }

                            tvHomeNum.setText(homeNum + "间");
                            //现在价格
                            tvOiMoney.setText(mPrepareBody.getActualPriceValue() + "");

                            //优惠
                            if (mPrepareBody.getTotalDiscountAmountValue() != null && !mPrepareBody.getTotalDiscountAmountValue().equals("0")) {
                                tvOiReduce.setText(Html.fromHtml("已优惠 &yen;" + mPrepareBody.getTotalDiscountAmountValue()));
                            } else {
                                tvOiReduce.setVisibility(View.GONE);
                            }


                            //是否需要填写邮箱
                            if (!mPrepareBody.isAllowEmail()) {
                                llOiEmail.setVisibility(View.GONE);
                                vwEmail.setVisibility(View.GONE);
                            }

                            tvOiTitle.setText(mPrepareBody.getProduct().getChildProduct().getRoomName());
                            tvOiBottom.setText(mPrepareBody.getProduct().getChildProduct().getRules());


                            //连住优惠
                            if (mPrepareBody.getStayDiscountAmountValue() != null) {
                                llReduceOld.setVisibility(View.VISIBLE);
                                tvReduceOld.setText(mPrepareBody.getStayDiscountAmountValue() + "");
                            } else {
                                llReduceOld.setVisibility(View.GONE);
                            }

                            //自住优惠
                            if (mPrepareBody.getDiscountList() != null && mPrepareBody.getDiscountList().size() > 0) {
                                llReduceMe.setVisibility(View.VISIBLE);
                                tvReduceMe.setText(Html.fromHtml("- &yen; " + mPrepareBody.getDiscountAmountValue()));
                            } else {
                                llReduceMe.setVisibility(View.GONE);
                            }

                            //优惠余额都不含有
                            if (!mPrepareBody.isAllowUseWallet() && (mPrepareBody.getDiscountAmountValue() == null || mPrepareBody.getDiscountAmountValue().equals("0"))) {
                                llReduceReduce.setVisibility(View.GONE);
                            } else {
                                llReduceReduce.setVisibility(View.VISIBLE);
                            }

                            if (mPrepareBody.getAddBrokerageAmountValue() != null && !mPrepareBody.getAddBrokerageAmountValue().equals("0")) {
                                vwOlAdd.setVisibility(View.VISIBLE);
                                tvOlAdd.setVisibility(View.VISIBLE);
                                String htmlStr = "加返" + "<font color='#F73637'>" + mPrepareBody.getAddBrokerageAmountValue() + "</font>元将会返还至您的佣金";
                                tvOlAdd.setText(Html.fromHtml(htmlStr));
                            } else {
                                vwOlAdd.setVisibility(View.GONE);
                                tvOlAdd.setVisibility(View.GONE);
                            }


                            //是否填写身份证号
                            mIsIdentity = mPrepareBody.isAllowIdentityNumber();

                            // 是否含有余额
                            if (mPrepareBody.isAllowUseWallet() && mPrepareBody.getWalletBalance() != 0 && mPrepareBody.getWalletBalanceValue() != null) {
                                rlOlHava.setVisibility(View.VISIBLE);
                                tvOiHas.setText(Html.fromHtml("当前可用余额 &yen;" + mPrepareBody.getWalletBalanceValue()));
                                ivBalanceCheckMoney.setText(Html.fromHtml("- &yen; " + mPrepareBody.getWalletDeductibleAmountValue()));
                            } else {
                                rlOlHava.setVisibility(View.GONE);
                            }


                            if (listData.size() == 0) {
                                for (int i = 0; i < homeNum; i++) {
                                    GuestPostEntity guestPostEntity = new GuestPostEntity();
                                    guestPostEntity.setAllowCn(mOrderPrepareEntity.getBody().isAllowNameCn());
                                    guestPostEntity.setAllowIdentityNumber(mOrderPrepareEntity.getBody().isAllowIdentityNumber());
                                    listData.add(guestPostEntity);
                                }
                            }
                            orderInputAdapter.setData(listData);
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String url, String error) {

            }
        });
    }


    /**
     * 账号检测
     *
     * @param text
     */
    @OnTextChanged(value = R.id.et_oi_feedBack, callback = OnTextChanged.Callback.AFTER_TEXT_CHANGED)
    public void etFeedbackChanged(CharSequence text) {
        tvOiNum.setText(text.toString().length() + "/50");
    }

    /**
     * 初始化列表
     */
    private void initRecycle() {
        rvOiIn.setLayoutManager(new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false));
        orderInputAdapter = new OrderInputAdapter(this, new View.OnClickListener() {
            @Override
            public void onClick(View v) {//打开通讯录
                Bundle bundle = new Bundle();
                bundle.putInt("HomeNum", homeNum);
                if (mReturnEntity != null && mReturnEntity.getBody() != null && mReturnEntity.getBody().size() > 0) {
                    bundle.putString("data", new Gson().toJson(mReturnEntity));
                } else {
                    bundle.putString("data", "default");
                }
                startActivityResult(ResidentActivity.class, Constant.Code.phoneCode, bundle);
            }
        });
        rvOiIn.setAdapter(orderInputAdapter);
        //监听子布局
        orderInputAdapter.setOnAddTextChangeLisnter(new OrderInputAdapter.onAddTextChangeLisnter() {
            @Override
            public void textChange(EditText editText, String text, int position) {
                switch (editText.getId()) {
                    case R.id.et_oi_home://房型
                        if (mPrepareBody.isAllowNameCn()) {
                            if (position < listData.size()) {
                                listData.get(position).setNameCn(text);
                            }
                        } else {
                            if (position < listData.size()) {
                                listData.get(position).setFamilyNameEn(text);
                            }
                        }
                        break;
                    case R.id.et_oi_card://银行卡
                        if (position < listData.size() && mPrepareBody.isAllowNameEn()) {
                            listData.get(position).setPassport(text);
                        }
                        listData.get(position).setIdcard(text);
                        break;
                    case R.id.et_oi_give://房型
                        if (position < listData.size()) {
                            listData.get(position).setGivenNameEn(text);
                        }
                        break;
                }
            }
        });
    }


    /**
     * 初始化popup
     */
    private void initPopupDetails() {
        try {
            popuDetails = new CommonPopupWindow(OrderInputActivity.this, R.layout.popu_money_details, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {

                @Override
                protected void initView() {
                    View view = getContentView();

                    TextView tvMe = (TextView) view.findViewById(R.id.tv_md_me);
                    LinearLayout llMe = (LinearLayout) view.findViewById(R.id.ll_md_me);

                    TextView tvBalance = (TextView) view.findViewById(R.id.tv_md_balance);
                    LinearLayout llBalance = (LinearLayout) view.findViewById(R.id.ll_md_balance);
                    TextView tvLeft = (TextView) view.findViewById(R.id.tv_md_left);
                    tvLeft.setText(Html.fromHtml("&yen;"));

                    TextView tvReduceTitle = (TextView) view.findViewById(R.id.tv_reduce_title);
                    TextView tvReduce = (TextView) view.findViewById(R.id.tv_md_reduce);
                    LinearLayout llReduce = (LinearLayout) view.findViewById(R.id.ll_md_reduce);
                    llReduce.setVisibility(View.GONE);
                    TextView tvOld = (TextView) view.findViewById(R.id.tv_md_old);
                    LinearLayout llOld = (LinearLayout) view.findViewById(R.id.ll_md_old);


                    TextView tvMdMoney = (TextView) view.findViewById(R.id.tv_md_money);

                    TextView tvMdConfirm = (TextView) view.findViewById(R.id.tv_md_confirm);
                    tvMdConfirm.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popuDetails.getPopupWindow().dismiss();
                            ivOiDetails.setImageResource(R.drawable.text_down);
                        }
                    });


                    tvMdMoney.setText(mPrepareBody.getActualPriceValue() + "");

                    if (mPrepareBody.getDiscountAmountValue() != null
                            && !mPrepareBody.getDiscountAmountValue().equals("")
                            && !mPrepareBody.getDiscountAmountValue().equals("0")) {
                        tvMe.setText(Html.fromHtml("- &yen;" + mPrepareBody.getDiscountAmountValue()));
                    } else {
                        llMe.setVisibility(View.GONE);
                    }

                    if (mPrepareBody.isAllowUseWallet() && userBalance) {
                        tvBalance.setText(Html.fromHtml("- &yen;" + mPrepareBody.getWalletDeductibleAmountValue()));
                    } else {
                        llBalance.setVisibility(View.GONE);
                    }

                    if (mPrepareBody.getStayDiscountAmountValue() != null && !mPrepareBody.getStayDiscountAmountValue().equals("")) {
                        tvOld.setText(Html.fromHtml("- &yen;" + mPrepareBody.getStayDiscountAmountValue()));
                    } else {
                        llOld.setVisibility(View.GONE);
                    }

                    if (!mPrepareBody.isAllowUseWallet() && mPrepareBody.getTotalDiscountAmountValue().equals("0")) {
                        tvReduceTitle.setVisibility(View.GONE);
                        llReduce.setVisibility(View.GONE);
                        llOld.setVisibility(View.GONE);
                        llBalance.setVisibility(View.GONE);
                        llMe.setVisibility(View.GONE);
                    }


                    List<OrderPrepareEntity.BodyBean.ProductBean.ChildProductBean.PriceListBean> priceList = mPrepareBody.getProduct().getChildProduct().getPriceList();
                    List<DataEntity> list = new ArrayList<>();
                    for (int i = 0; i < priceList.size(); i++) {
                        DataEntity dataEntity = new DataEntity();
                        dataEntity.setTitle(priceList.get(i).getDayValue());
                        dataEntity.setContent(priceList.get(i).getPriceValue());
                        list.add(dataEntity);
                    }
                    RecyclerView rvDetails = (RecyclerView) view.findViewById(R.id.rv_md_details);
                    rvDetails.setLayoutManager(new LinearLayoutManager(OrderInputActivity.this, LinearLayoutManager.VERTICAL, false));
                    OrderDeatailsPopuAdapter orderDeatailsPopuAdapter = new OrderDeatailsPopuAdapter(OrderInputActivity.this);
                    rvDetails.setAdapter(orderDeatailsPopuAdapter);
                    orderDeatailsPopuAdapter.setData(list);


                    LinearLayout llConfirm = view.findViewById(R.id.ll_popup_confirm);
                    LinearLayout llBottom = view.findViewById(R.id.ll_bottom);
                    llBottom.setVisibility(View.VISIBLE);
                    llConfirm.setVisibility(View.GONE);

                    TextView textView = view.findViewById(R.id.tv_oi_confirm);
                    textView.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            initConfirm();
                        }
                    });

                    LinearLayout linearLayout = view.findViewById(R.id.ll_ol_details);
                    linearLayout.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popuDetails.getPopupWindow().dismiss();
                            ivOiDetails.setImageResource(R.drawable.text_down);
                        }
                    });
                    TextView tvMoney = view.findViewById(R.id.tv_oi_money);
                    ImageView ivOiDetails = view.findViewById(R.id.iv_oi_details);
                    TextView tvOiReduce = view.findViewById(R.id.tv_oi_reduce);

                    ivOiDetails.setImageResource(R.drawable.text_up);
                    tvMoney.setText(mPrepareBody.getActualPriceValue() + "");
                    if (mPrepareBody.getTotalDiscountAmountValue() != null && !mPrepareBody.getTotalDiscountAmountValue().equals("0")) {
                        tvOiReduce.setText(Html.fromHtml("已优惠 &yen;" + mPrepareBody.getTotalDiscountAmountValue()));
                    } else {
                        tvOiReduce.setVisibility(View.GONE);
                    }
                }

                @Override
                protected void initEvent() {
                    WindowManager.LayoutParams attributes = getWindow().getAttributes();
                    attributes.alpha = 0.3f;
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    getWindow().setAttributes(attributes);
                }
            };
            popuDetails.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams attributes = getWindow().getAttributes();
                    attributes.alpha = 1.0f;
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    getWindow().setAttributes(attributes);
                }
            });
            popuDetails.showAtLocation(llOl, Gravity.BOTTOM, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onBackPressed() {
        ConfirmReturnDialog confirmDialog = ConfirmReturnDialog.newInstance("提示", "该产品十分抢手，喜欢就尽快提交订单把", "我再想想", "继续预订");
        confirmDialog.setOnBtnClickListener(new ConfirmReturnDialog.OnBtnClickListener() {
            @Override
            public void onBtnClick(View view) {

            }

            @Override
            public void onDeselect(View view) {
                finish();
            }
        });
        confirmDialog.show(getSupportFragmentManager(), "返回");
    }


    /**
     * 点击事件
     *
     * @param view
     */
    @OnClick({R.id.iv_title, R.id.ll_ol_house_details, R.id.ll_ol_details, R.id.tv_oi_confirm, R.id.iv_oi_reduce
            , R.id.iv_oi_add, R.id.iv_balance_check_money, R.id.iv_balance_check, R.id.iv_oi_phone})
    public void btnOnclick(View view) {
        try {
            switch (view.getId()) {
                case R.id.iv_title://返回
                    onBackPressed();
                    break;
                case R.id.ll_ol_house_details://房型明细
                    initPopupMore();
                    break;
                case R.id.ll_ol_details://房费明细
                    initPopupDetails();
                    break;
                case R.id.tv_oi_confirm://确定
                    initConfirm();
                    break;
                case R.id.iv_oi_reduce://减少
                    if (homeNum > minNum) {//房间数量大于最小数量
                        //UI控制
                        homeNum--;
                        tvHomeNum.setText(homeNum + "间");

                        ivOiAdd.setImageResource(R.drawable.ic_oi_add);
                        if (homeNum == minNum) {
                            ivOiReduce.setImageResource(R.drawable.ic_oi_reduce_light);
                        }

                        if (mReturnEntity != null && mReturnEntity.getBody() != null) {
                            boolean isDelete = true;
                            for (int i = mReturnEntity.getBody().size() - 1; i >= 0; i--) {
                                if (isDelete &&
                                        ((mPrepareBody.isAllowNameCn() && mReturnEntity.getBody().get(i).getNameCn().equals(listData.get(listData.size() - 1).getNameCn()))
                                                || (mPrepareBody.isAllowNameEn()
                                                && mReturnEntity.getBody().get(i).getFamilyNameEn().equals(listData.get(listData.size() - 1).getFamilyNameEn())
                                                && mReturnEntity.getBody().get(i).getGivenNameEn().equals(listData.get(listData.size() - 1).getGivenNameEn())))) {
                                    mReturnEntity.getBody().get(i).setPreferred(false);
                                    isDelete = false;
                                }
                            }
                        }

                        listData.remove(listData.size() - 1);
                        initPrepare();
                    } else {
                        ivOiReduce.setImageResource(R.drawable.ic_oi_reduce_light);
                        ToastUtil.initToast(this, "已到达最小选择房间数量");
                    }
                    break;
                case R.id.iv_oi_add://增加
                    if (homeNum < maxNum) {
                        homeNum++;
                        tvHomeNum.setText(homeNum + "间");

                        ivOiReduce.setImageResource(R.drawable.ic_oi_reduce);
                        if (homeNum == maxNum) {
                            ivOiAdd.setImageResource(R.drawable.ic_oi_add_light);
                        }

                        GuestPostEntity guestPostEntity = new GuestPostEntity();
                        guestPostEntity.setNameCn("");
                        guestPostEntity.setFamilyNameEn("");
                        guestPostEntity.setGivenNameEn("");
                        guestPostEntity.setAllowCn(mOrderPrepareEntity.getBody().isAllowNameCn());
                        guestPostEntity.setAllowIdentityNumber(mOrderPrepareEntity.getBody().isAllowIdentityNumber());
                        listData.add(guestPostEntity);
                        initPrepare();
                    } else {
                        ivOiAdd.setImageResource(R.drawable.ic_oi_add_light);
                        ToastUtil.initToast(this, "已到达最大限购房间数量");
                    }
                    break;
                case R.id.iv_balance_check_money://选择是否使用余额
                case R.id.iv_balance_check:
                    userBalance = !userBalance;
                    if (userBalance) {
                        ivBalanceCheck.setImageResource(R.drawable.public_small_check_selected);
                    } else {
                        ivBalanceCheck.setImageResource(R.drawable.public_small_check);
                    }
                    initPrepare();
                    break;
                case R.id.iv_oi_phone:
                    //**版本判断。当手机系统大于 23 时，才有必要去判断权限是否获取**
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        //ContextCompat.checkSelfPermission() 方法 指定context和某个权限 返回PackageManager.PERMISSION_DENIED或者PackageManager.PERMISSION_GRANTED
                        if (ContextCompat.checkSelfPermission(OrderInputActivity.this, Manifest.permission.READ_CONTACTS)
                                != PackageManager.PERMISSION_GRANTED) {
                            // 若不为GRANTED(即为DENIED)则要申请权限了
                            // 申请权限 第一个为context 第二个可以指定多个请求的权限 第三个参数为请求码
                            ActivityCompat.requestPermissions(OrderInputActivity.this,
                                    new String[]{Manifest.permission.READ_CONTACTS},
                                    69);
                        } else {
                            //权限已经被授予，在这里直接写要执行的相应方法即可
                            intentToContact();
                        }
                    } else {
                        // 低于6.0的手机直接访问
                        intentToContact();
                    }
                    break;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void initConfirm() {
        try {
            int position = 0;
            int isOk = 0;
            for (int i = 0; i < listData.size(); i++) {
                if (mOrderPrepareEntity.getBody().isAllowNameCn() && listData.get(i).getNameCn().length() == 0 && isOk == 0) {
                    position = i;
                    isOk = 1;
                }


                if (isOk == 0 && mOrderPrepareEntity.getBody().isAllowNameEn()
                        && (listData.get(i).getFamilyNameEn() == null || listData.get(i).getGivenNameEn() == null)) {
                    position = i;
                    isOk = 2;
                }
            }
            if (isOk == 1) {
                ToastUtil.initToast(this, "请输入房间" + (position + 1) + "的入住人");
            } else if (isOk == 2) {
                ToastUtil.initToast(this, "请输入房间" + (position + 1) + "的英文姓名");
            } else if (etOiPhone.getText().length() == 0) {
                ToastUtil.initToast(this, "请输入接收预定信息的手机号码");
                llOiError.setVisibility(View.VISIBLE);
                tvOiError.setText("请输入手机号码");
            } else if (!RegexUtil.checkLoginData(etOiPhone.getText().toString())) {
                ToastUtil.initToast(this, "请输入正确手机号码");
                llOiError.setVisibility(View.VISIBLE);
                tvOiError.setText("请输入正确手机号码");
            } else if (mPrepareBody.isAllowEmail() && etOiEmail.getText().length() == 0) {
                ToastUtil.initToast(this, "请输入邮箱号码");
            } else if (mPrepareBody.isAllowEmail() && !RegexUtil.checkRegexEmailData(etOiEmail.getText().toString())) {
                ToastUtil.initToast(this, "请输入正确的邮箱号码");
            } else {
                showDialog();
                OrdersPostEntity ordersPostEntity = new OrdersPostEntity();
                ordersPostEntity.setType(15);
                OrdersPostEntity.ProductBean productBean = new OrdersPostEntity.ProductBean();
                productBean.setId(mDetailsBean.getId());
                productBean.setRoomTypeId(mBodyBean.getId());
                productBean.setSalePlanId(mSalePlansBean.getId());
                productBean.setType(99);
                productBean.setQuantity(homeNum);
                ordersPostEntity.setProduct(productBean);

                ordersPostEntity.setMobile(etOiPhone.getText().toString());
                ordersPostEntity.setLinkman(listData.get(0).getNameCn());

                List<OrdersPostEntity.GuestsBean> guests = new ArrayList<>();
                for (int i = 0; i < listData.size(); i++) {
                    OrdersPostEntity.GuestsBean guestsBean = new OrdersPostEntity.GuestsBean();

                    if (mIsIdentity) {
                        guestsBean.setIdcard(listData.get(i).getIdcard());
                    }
                    guestsBean.setMobile(etOiPhone.getText().toString());
                    guestsBean.setEmail(etOiEmail.getText().toString());
                    guests.add(guestsBean);

                    if (mOrderPrepareEntity.getBody().isAllowNameCn()) {
                        guestsBean.setLinkman(listData.get(i).getNameCn());
                    }

                    if (mOrderPrepareEntity.getBody().isAllowNameEn()) {
                        guestsBean.setFamilyNameEn(listData.get(i).getFamilyNameEn());
                        guestsBean.setGivenNameEn(listData.get(i).getGivenNameEn());
                    }
                    guestsBean.setPassport(listData.get(i).getPassport());
                }

                ordersPostEntity.setGuests(guests);
                ordersPostEntity.setCheckInDate(mCheckInDate);
                ordersPostEntity.setCheckOutDate(mCheckOutDate);
                ordersPostEntity.setUseWallet(userBalance);
                ordersPostEntity.setWalletDeductibleAmount(userBalance ? promotionNum : 0);
                ordersPostEntity.setAddressId(mAddress);
                ordersPostEntity.setEmail(etOiEmail.getText().toString());
                ordersPostEntity.setRemarks(etOiFeedBack.getText().toString());
                LogUtil.jLog().e(new Gson().toJson(ordersPostEntity));
                Map<String, Object> map = new HashMap<>();
                OkHttpUtil.postJson(this, Constant.URL.createOrders, ordersPostEntity, map, new OkHttpUtil.OnDataListener() {

                    @Override
                    public void onResponse(String url, String json) {
                        LogUtil.jLog().e(json);
                        dismissDialog();
                        try {
                            CreatOrdersEntity creatOrdersEntity = new Gson().fromJson(json, CreatOrdersEntity.class);
                            if (creatOrdersEntity.getCode().equals(Constant.Strings.SUC)) {
                                Bundle bundle = new Bundle();
                                bundle.putString("data", json);
                                bundle.putString("inDay", homeDay + "");
                                bundle.putString("feedBack", etOiFeedBack.getText().toString() + "");

                                startActivity(OrderInputResultActivity.class, bundle);
                                finish();
                            } else {
                                ToastUtil.initToast(OrderInputActivity.this, creatOrdersEntity.getMsg());
                            }
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(String url, String error) {

                    }
                });
            }
        } catch (Exception e) {
            ToastUtil.initToast(getApplicationContext(), "出现未知错误，请联系客服人员！");
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == 69) {
            if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                intentToContact();
            } else {
                Toast.makeText(OrderInputActivity.this, "授权被禁止", Toast.LENGTH_SHORT).show();
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions,
                grantResults);
    }

    /**
     * 跳转到联系人界面
     */
    private void intentToContact() {
        // 跳转到联系人界面
        Intent intent = new Intent();
        intent.setAction("android.intent.action.PICK");
        intent.addCategory("android.intent.category.DEFAULT");
        intent.setType("vnd.android.cursor.dir/phone_v2");
        startActivityForResult(intent, 0x30);
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case 0x30:
                if (data != null) {
                    Uri uri = data.getData();
                    String phoneNum = null;
                    String contactName = null;
                    // 创建内容解析者
                    ContentResolver contentResolver = getContentResolver();
                    Cursor cursor = null;
                    if (uri != null) {
                        cursor = contentResolver.query(uri,
                                new String[]{"display_name", "data1"}, null, null, null);
                    }
                    while (cursor.moveToNext()) {
                        contactName = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                        phoneNum = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                    }
                    cursor.close();
                    //  把电话号码中的  -  符号 替换成空格
                    if (phoneNum != null) {
                        phoneNum = phoneNum.replaceAll("-", " ");
                        // 空格去掉  为什么不直接-替换成"" 因为测试的时候发现还是会有空格 只能这么处理
                        phoneNum = phoneNum.replaceAll(" ", "");
                    }
                    etOiPhone.setText(phoneNum);
                }
                break;
            case Constant.Code.phoneCode:
                if (resultCode == RESULT_OK) {
                    Bundle bundle = data.getBundleExtra("bundle");
                    String data1 = bundle.getString("data");
                    mReturnEntity = new Gson().fromJson(data1, MemberGuestEntity.class);
                    if (mReturnEntity != null) {
                        for (int i = 0; i < listData.size(); i++) {
                            listData.get(i).setNameCn("");
                            listData.get(i).setFamilyNameEn("");
                            listData.get(i).setGivenNameEn("");
                        }


                        List<MemberGuestEntity.BodyBean> body = mReturnEntity.getBody();
                        List<MemberGuestEntity.BodyBean> checkBody = new ArrayList<>();
                        for (int i = 0; i < body.size(); i++) {
                            if (body.get(i).isPreferred()) {
                                checkBody.add(body.get(i));
                            }
                        }

                        if (checkBody.size() >= listData.size()) {
                            int num = 0;
                            for (int i = listData.size() - 1; i >= 0; i--) {
                                if (num < checkBody.size()) {
                                    if (mPrepareBody.isAllowNameCn()) {
                                        listData.get(i).setNameCn(checkBody.get(num).getNameCn());
                                        if (mPrepareBody.isAllowIdentityNumber()) {
                                            listData.get(i).setIdcard(checkBody.get(num).getIdcard());
                                        }
                                    } else {
                                        listData.get(i).setFamilyNameEn(checkBody.get(num).getFamilyNameEn());
                                        listData.get(i).setGivenNameEn(checkBody.get(num).getGivenNameEn());
                                        if (mPrepareBody.isAllowIdentityNumber()) {
                                            listData.get(i).setPassport(checkBody.get(num).getPassport());
                                            listData.get(i).setIdcard(checkBody.get(num).getIdcard());
                                        }
                                    }
                                }
                                num++;
                            }
                        } else {
                            for (int i = listData.size() - 1; i >= 0; i--) {
                                if (i < checkBody.size()) {
                                    if (mPrepareBody.isAllowNameCn()) {
                                        listData.get(i).setNameCn(checkBody.get(i).getNameCn());
                                        if (mPrepareBody.isAllowIdentityNumber()) {
                                            listData.get(i).setIdcard(checkBody.get(i).getIdcard());
                                        }
                                    } else {
                                        listData.get(i).setFamilyNameEn(checkBody.get(i).getFamilyNameEn());
                                        listData.get(i).setGivenNameEn(checkBody.get(i).getGivenNameEn());
                                        if (mPrepareBody.isAllowIdentityNumber()) {
                                            listData.get(i).setPassport(checkBody.get(i).getPassport());
                                            listData.get(i).setIdcard(checkBody.get(i).getIdcard());
                                        }
                                    }
                                }
                            }
                        }

                        orderInputAdapter.setData(listData);
                    }
                }

                break;
        }
    }


    private void initPopupMore() {
        try {
            popupMore = new CommonPopupWindow(OrderInputActivity.this, R.layout.popu_house_type, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT) {

                @Override
                protected void initView() {
                    View view = getContentView();
                    view.findViewById(R.id.tv_ht_confirm).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupMore.getPopupWindow().dismiss();
                        }
                    });
                    view.findViewById(R.id.tv_dismiss).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            popupMore.getPopupWindow().dismiss();
                        }
                    });

                    TextView tvHtTitle = (TextView) view.findViewById(R.id.tv_ht_title);
                    TextView tvTitle = (TextView) view.findViewById(R.id.tv_pop_title);
                    TextView tvTitleRight = (TextView) view.findViewById(R.id.tv_pop_title_right);
                    TextView tvTitleContent = (TextView) view.findViewById(R.id.tv_pop_title_content);

                    TextView tvPopEat = (TextView) view.findViewById(R.id.tv_pop_eat);
                    TextView tvEatContent = (TextView) view.findViewById(R.id.tv_pop_eat_content);
                    TextView tvBed = (TextView) view.findViewById(R.id.tv_pop_bed);
                    TextView tvBedContent = (TextView) view.findViewById(R.id.tv_pop_bed_content);

                    tvHtTitle.setText(mBodyBean.getName());
                    tvTitle.setText(mSalePlansBean.getBaseDesc().getName());
                    tvTitleRight.setText("(" + mSalePlansBean.getName() + ")");
                    tvTitleContent.setText(mSalePlansBean.getBaseDesc().getContent());

                    tvPopEat.setText(mSalePlansBean.getFoodDesc().getName());

                    if (mSalePlansBean.getFoodDesc().getSubName() == null || mSalePlansBean.getFoodDesc().getSubName().length() == 0) {
                        tvEatContent.setVisibility(View.GONE);
                    } else {
                        tvEatContent.setText(mSalePlansBean.getFoodDesc().getSubName());
                    }

                    tvBed.setText(mSalePlansBean.getBedDesc().getName());
                    tvBedContent.setText(mSalePlansBean.getBedDesc().getContent());


                    RecyclerView recyclerView = view.findViewById(R.id.rv_pop);
                    recyclerView.setLayoutManager(new GridLayoutManager(OrderInputActivity.this, 2));

                    List<HotelRoomEntity.BodyBean.FacilitiesBean> facilities = mBodyBean.getFacilities();
                    List<DataEntity> dataEntities = new ArrayList<>();
                    if (facilities != null && facilities.size() > 0) {
                        view.findViewById(R.id.tv_pop_base_title).setVisibility(View.VISIBLE);
                        for (int i = 0; i < facilities.size(); i++) {
                            for (int j = 0; j < facilities.get(i).getList().size(); j++) {
                                DataEntity dataEntity = new DataEntity();
                                dataEntity.setTitle(facilities.get(i).getList().get(j).getName());
                                dataEntities.add(dataEntity);
                            }
                        }
                    } else {
                        view.findViewById(R.id.tv_pop_base_title).setVisibility(View.GONE);
                    }


                    PopularHouseAdapter popularHouseAdapter = new PopularHouseAdapter(OrderInputActivity.this);
                    recyclerView.setAdapter(popularHouseAdapter);
                    popularHouseAdapter.setData(dataEntities);

                    if (null != mBodyBean.getImageURLs() && mBodyBean.getImageURLs().size() > 0) {
                        view.findViewById(R.id.rl_bus).setVisibility(View.VISIBLE);
                        //Banner适配
                        BannerUtils bannerUtils1 = view.findViewById(R.id.bus_ht);
                        bannerUtils1.setAdapter(new BannerUtils.Adapter() {
                            @Override
                            public void fillBannerItem(BannerUtils bannerUtils, View itemView, Object model, int position) {
                                RequestOptions options = new RequestOptions()
                                        .error(R.drawable.map_img2x)
                                        .dontAnimate()
                                        .centerCrop()
                                        .placeholder(R.drawable.map_img2x);
                                Glide.with(itemView.getContext())
                                        .load(model)
                                        .apply(options)
                                        .into((ImageView) itemView);
                            }
                        });

                        List<String> urlString = new ArrayList<>();
                        List<String> idString = new ArrayList<>();
                        final List<String> imageURLs = mBodyBean.getImageURLs();
                        for (int i = 0; i < imageURLs.size(); i++) {
                            urlString.add(mBodyBean.getImageURLs().get(i));
                            idString.add("空的");
                        }
                        bannerUtils1.setData(R.layout.view_image_circle, urlString, idString);

                        tvGuideMore = view.findViewById(R.id.tv_guide);
                        bannerUtils1.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
                            @Override
                            public void onPageScrolled(int i, float v, int i1) {
                                if (v % 1 > 0.1 && imageURLs.size() > i + 1) {
                                    tvGuideMore.setText(i + 2 + "/" + imageURLs.size());
                                } else {
                                    tvGuideMore.setText(i + 1 + "/" + imageURLs.size());
                                }
                            }

                            @Override
                            public void onPageSelected(int i) {

                            }

                            @Override
                            public void onPageScrollStateChanged(int i) {

                            }
                        });
                    } else {
                        view.findViewById(R.id.rl_bus).setVisibility(View.GONE);
                    }
                }

                @Override
                protected void initEvent() {
                    WindowManager.LayoutParams attributes = getWindow().getAttributes();
                    attributes.alpha = 0.3f;
                    getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    getWindow().setAttributes(attributes);
                }
            };
            popupMore.getPopupWindow().setOnDismissListener(new PopupWindow.OnDismissListener() {
                @Override
                public void onDismiss() {
                    WindowManager.LayoutParams attributes = getWindow().getAttributes();
                    attributes.alpha = 1.0f;
                    getWindow().clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                    getWindow().setAttributes(attributes);
                }
            });
            popupMore.showAtLocation(llOl, Gravity.BOTTOM, 0, 0);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 停止加载框
     */
    protected void dismissDialog() {
        if (loadDialog != null) {
            loadDialog.dismiss();//获取信息后关闭对话框
        }
    }

    /**
     * 设置加载框
     */
    protected void showDialog() {
        if (loadDialog == null) {
            loadDialog = LoadDialog.newInstance("加载中");
        }
        loadDialog.show(getSupportFragmentManager(), "loading");
    }
}
